﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
//
using OsPortal;
using System.Data.SqlClient;
using System.Data;

/// <summary>
/// Summary description for clsUsers
/// </summary>
public class clsUsers
{
    static string strClassName = "clsUsers";

    public struct stUSER
    {
        public String strUS_ID;
        public String strUS_EMAIL;
        public String strUS_MATKHAU;
        public String strUS_HOTEN;
        public String strUS_AVATAR;
        public String strUS_DIACHI;
        public String strUS_DIENTHOAI;
        public String strUS_MAKICHHOAT;
        public Boolean blUS_NHANMAIL;
        public String strUS_OLDPASS;
        public String strUS_NEWPASS;
    }

    public clsUsers()
    {
        //
        // TODO: Add constructor logic here
        //
    }


    /// <summary>
    /// Get User
    /// </summary>
    /// <param name="iCurrPage"></param>
    /// <param name="iPageSize"></param>
    /// <param name="strUS_ID"></param>
    /// <param name="strUS_EMAIL"></param>
    /// <param name="strUS_HOTEN"></param>
    /// <param name="iUS_TRANGTHAIKICHHOAT"></param>
    /// <param name="iUS_MOIGIOI"></param>
    /// <returns></returns>
    public static DataSet USER_FND(int iCurrPage
                                        , int iPageSize
                                        , string strUS_ID
                                        , string strUS_EMAIL
                                        , string strUS_HOTEN
                                        , int iUS_TRANGTHAIKICHHOAT
                                        , int iUS_MOIGIOI)
    {
        DataSet dtData = null;
        try
        {
            dtData = oSqlDataHelper.sExecuteDataSet("USERS_FND", new SqlParameter[]{
                new SqlParameter("@P_CURRPAGE",iCurrPage)
                ,new SqlParameter("@P_PAGESIZE",iPageSize)
                ,new SqlParameter("@P_US_ID",strUS_ID)
                ,new SqlParameter("@P_US_EMAIL",strUS_EMAIL)
                ,new SqlParameter("@P_US_HOTEN",strUS_HOTEN)
                ,new SqlParameter("@P_US_TRANGTHAIKICHHOAT",iUS_TRANGTHAIKICHHOAT)
                ,new SqlParameter("@P_US_MOIGIOI",iUS_MOIGIOI)
            });
            return dtData;
        }
        catch (Exception ex)
        {
            OsPortal.oFileHelper.WriteLogErr(strClassName, "USERS_FND", ex.ToString());
            return null;
        }
        finally
        {
            //dtData.Dispose();
        }
    }

    /// <summary>
    /// Function Name: KIỂM TRA ĐĂNG NHẬP
    /// Create Date: 2011
    /// Update Date:
    /// Author: Thuannh
    /// </summary>
    /// <param name="strEmail">Email</param>
    /// <param name="strPassword">Password</param>
    /// <returns>0: Nếu tài khoản ko tồn tại - 1:Tài khoản đã bị khóa - 2:OK</returns>
    public static string fncDoLogin(string strEmail, string strPassword)
    {
        try
        {
            strPassword = oStringHelper.EncryptStringSHA1(strPassword);
            DataSet dtUsers = null;
            dtUsers = oSqlDataHelper.sExecuteDataSet("USERS_ACT_CHECKLOGIN", new SqlParameter[]{
            new SqlParameter("@P_US_EMAIL",strEmail),
            new SqlParameter("@P_US_MATKHAU",strPassword),
            });
            if (dtUsers == null) return "";
            if (dtUsers.Tables[1].Rows.Count > 0)
            {
                int iErrID = OsPortal.oStringHelper.fncCnvNullToInt(dtUsers.Tables[1].Rows[0]["ERRID"]);
                string strErrName = dtUsers.Tables[1].Rows[0]["ERRNAME"].ToString();

                if (iErrID > 0)
                {
                    return strErrName;
                }
            }

            /*--------------------------Add info user to cooke-----------------------------------------------*/
            HttpCookie userInfo = new HttpCookie(basConst.COOKIE_USER_INFO); //Tao object lu thong tin users
            userInfo.Expires = DateTime.Now.AddDays(basConst.timeCookie); // thoi gian song cua cookie
            userInfo[basConst.COOKIE_USER_ID] = dtUsers.Tables[0].Rows[0]["US_ID"].ToString(); ;
            userInfo[basConst.COOKIE_USER_NAME] = dtUsers.Tables[0].Rows[0]["US_HOTEN"].ToString();
            userInfo[basConst.COOKIE_USER_EMAIL] = dtUsers.Tables[0].Rows[0]["US_EMAIL"].ToString();
            userInfo[basConst.COOKIE_USER_LASTLOGIN] = dtUsers.Tables[0].Rows[0]["US_LASTLOGIN"].ToString();
            userInfo.Expires.Add(new TimeSpan(0, 1, 0));
            HttpContext.Current.Response.Cookies.Add(userInfo);
            /*----------------------------------------------------------------------------------------------*/
            return "1";
        }
        catch (Exception ex)
        {
            OsPortal.oFileHelper.WriteLogErr(strClassName, "Users_CheckLogIn", ex.ToString());
            return ex.ToString();
        }
    }

    /// <summary>
    /// ACT USER: ADD, EDIT, DELETE, CHANGEPASS
    /// Author: NguyenTV - 24/09/2013
    /// </summary>
    /// <param name="strMod"></param>
    /// <param name="objUser"></param>
    /// <param name="strError"></param>
    /// <returns></returns>
    public static bool USER_ACT(string strMod, clsUsers.stUSER objUser, out string strError)
    {
        try
        {
            string strUserID = objUser.strUS_ID;
            if (strMod == basConst.MOD_ADD)
            {
                strUserID = clsCommon.fncAutoCreateID("US", "users", "US_ID");
            }
            string strMatKhau = oStringHelper.EncryptStringSHA1(OsPortal.oStringHelper.fncCnvNullToString(objUser.strUS_MATKHAU));
            //
            string strMatKhau_old = oStringHelper.EncryptStringSHA1(OsPortal.oStringHelper.fncCnvNullToString(objUser.strUS_OLDPASS));
            string strMatKhau_new = oStringHelper.EncryptStringSHA1(OsPortal.oStringHelper.fncCnvNullToString(objUser.strUS_NEWPASS));
            DataTable tblResult;
            tblResult = oSqlDataHelper.sExecuteDataTable("USERS_ACT", new SqlParameter[]{
                                                     new SqlParameter("@P_MOD",strMod)
                                                    ,new SqlParameter("@P_US_ID",strUserID)
                                                    ,new SqlParameter("@P_US_EMAIL",objUser.strUS_EMAIL)
                                                    ,new SqlParameter("@P_US_MATKHAU",strMatKhau)
                                                    ,new SqlParameter("@P_US_HOTEN",objUser.strUS_HOTEN)
                                                    ,new SqlParameter("@P_US_AVATAR",objUser.strUS_AVATAR)
                                                    ,new SqlParameter("@P_US_DIACHI",objUser.strUS_DIACHI)
                                                    ,new SqlParameter("@P_US_DIENTHOAI",objUser.strUS_DIENTHOAI)
                                                    ,new SqlParameter("@P_US_MAKICHHOAT",objUser.strUS_MAKICHHOAT)
                                                    ,new SqlParameter("@P_US_NHANMAIL",objUser.blUS_NHANMAIL)
                                                    ,new SqlParameter("@P_US_OLDPASS",strMatKhau_old)
                                                    ,new SqlParameter("@P_US_NEWPASS",strMatKhau_new)
            });
            if (tblResult == null) { strError = ""; return true; }
            if (tblResult.Rows.Count <= 0) { strError = ""; return true; }
            //
            strError = OsPortal.oStringHelper.fncCnvNullToString(tblResult.Rows[0]["ERRNAME"]);
            return false;
        }
        catch (Exception ex)
        {
            OsPortal.oFileHelper.WriteLogErr(strClassName, "USER_ACT", ex.ToString());
            strError = "Có lỗi phát sinh, vui lòng liên hệ BQT";
            return false;
        }

    }

    /// <summary>
    /// Cấp lại mật khẩu qua Email
    /// Author: Nguyentv - 07/10/2013
    /// </summary>
    /// <param name="objUsers"></param>
    /// <param name="strError"></param>
    /// <returns></returns>
    public static bool fncNewsPas_by_Email(clsUsers.stUSER objUsers, out string strError)
    {
        try
        {
            string strMatKhau = oStringHelper.EncryptStringSHA1(OsPortal.oStringHelper.fncCnvNullToString(objUsers.strUS_MATKHAU));
            DataTable tblResult;
            tblResult = oSqlDataHelper.sExecuteDataTable("USERS_NEWSPASS_BY_EMAIL", new SqlParameter[]{
                                                     new SqlParameter("@P_US_EMAIL",objUsers.strUS_EMAIL)
                                                    ,new SqlParameter("@P_US_MATKHAU",strMatKhau)
            });
            if (tblResult == null) { strError = ""; return true; }
            if (tblResult.Rows.Count <= 0) { strError = ""; return true; }
            //
            strError = OsPortal.oStringHelper.fncCnvNullToString(tblResult.Rows[0]["ERRNAME"]);
            return false;
        }
        catch (Exception ex)
        {
            OsPortal.oFileHelper.WriteLogErr(strClassName, "fncNewsPas_by_Email", ex.ToString());
            strError = "Có lỗi phát sinh, vui lòng liên hệ BQT";
            return false;
        }
    }

    /// <summary>
    /// LẤY MÃ USER ĐƯỢC LƯU TRONG COOKIE
    /// Author: NguyenTV
    /// Create: 20/08/2013
    /// </summary>
    /// <returns></returns>
    public static string Users_GetValueCooKie(string strKey)
    {
        string strValues = "";
        try
        {
            HttpCookie reqCookies = HttpContext.Current.Request.Cookies[basConst.COOKIE_USER_INFO];
            if (reqCookies != null)
            {
                strValues = reqCookies[strKey].ToString();
            }
        }
        catch (Exception ex)
        {
            OsPortal.oFileHelper.WriteLogErr(strClassName, "Users_GetValueCooKie", ex.ToString());
        }
        return strValues;
    }

    /// <summary>
    /// Kiểm tra user đã đăng nhập chưa?
    /// </summary>
    /// <returns>true nếu đã đăng nhập - false nếu chưa</returns>
    public static bool CheckLoginUser_Client()
    {
        try
        {
            HttpCookie reqCookies = HttpContext.Current.Request.Cookies[basConst.COOKIE_USER_INFO];
            if (reqCookies != null)
            {
                string strUserID = reqCookies[basConst.COOKIE_USER_ID].ToString();
                if (!string.IsNullOrEmpty(strUserID)) return true;
            }
        }
        catch (Exception ex)
        {
            OsPortal.oFileHelper.WriteLogErr(strClassName, "CheckLoginUser_Client", ex.ToString());
        }
        return false;
    }


    /// <summary>
    /// Log out users
    /// </summary>
    public static void LogOutUsers()
    {
        try
        {
            if (HttpContext.Current.Request.Cookies[basConst.COOKIE_USER_INFO] != null)
            {
                HttpCookie myCookie = new HttpCookie(basConst.COOKIE_USER_INFO);
                myCookie.Expires = DateTime.Now.AddDays(-1d);
                HttpContext.Current.Response.Cookies.Add(myCookie);
            }
        }
        catch (Exception ex)
        {
            OsPortal.oFileHelper.WriteLogErr(strClassName, "LogOutUsers", ex.ToString());
        }
    }

    // <summary>
    /// Function Name: Kích hoạt tài khoản
    /// Create Date: 30/09.2013
    /// Update Date:
    /// Author: NguyenTv
    /// </summary>
    /// <param name="strEmail">Email</param>
    /// <param name="strActiveCode">Mã kích hoạt</param>
    /// <param name="_page"></param>
    /// <returns></returns>
    public static bool fncUser_KichHoat(string strMaKichHoat, System.Web.UI.Page _page)
    {
        int kq = 0;
        try
        {
            DataTable dt = oSqlDataHelper.sExecuteDataTable("USER_ACTIVE", new SqlParameter[]{
            new SqlParameter("@US_MAKICHHOAT",strMaKichHoat),
            });
            kq = Convert.ToInt16(dt.Rows[0]["KQ"]);
        }
        catch (Exception ex)
        {
            OsPortal.oFileHelper.WriteLogErr(strClassName, "fncUser_KichHoat", ex.ToString());
        }
        if (kq > 0) return true;
        return false;
    }

    /// <summary>
    /// Nap Gold
    /// </summary>
    /// <param name="strUserID">Ma Users</param>
    /// <param name="intGold">So Gold</param>
    /// <returns></returns>
    public static bool fncNapGold(string strUserID,string strSeria,string strCode, string strNhaMang, double intGold)
    {
        try
        {
            oSqlDataHelper.sExecute("USERS_ACT_NAP_GOLD", new SqlParameter[]{
            new SqlParameter("@P_US_ID", strUserID),
            new SqlParameter("@P_SERIA", strSeria),
            new SqlParameter("@P_CODE", strCode),
            new SqlParameter("@P_NHAMANG", strNhaMang),
            new SqlParameter("@P_GOLD", intGold),
            });
        }
        catch (Exception ex)
        {
            OsPortal.oFileHelper.WriteLogErr(strClassName, "fncNapGold", ex.ToString());
            return false;
        }
        return true;
    }

}